package com.qf.air.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.qf.air.constants.AirConstants;
import com.qf.air.entity.User;
import com.qf.air.service.UserService;
import com.qf.air.util.JSONUtil;
import com.qf.air.util.R;
import com.qf.air.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 维多利加
 * @Date: 2021/3/28 16:41
 */
@RestController
@RequestMapping("/user")
@CrossOrigin(allowCredentials = "true")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     # 请求路径&请求方式
     POST 	http://localhost/user/signin
     # 请求参数
     username = 用户名
     password = 密码
     */
    @PostMapping("/signin")
    public ResultVO signin(String username, String password, HttpServletResponse resp) throws JsonProcessingException {
        //1. 校验参数
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            System.out.println("用户名和密码均为必填项，岂能为空！");
            return R.error(222,"用户名和密码均为必填项，岂能为空！");
        }

        //2. 调用service执行登录
        User user = userService.login(username, password);



//        3. 将登录成功的用户信息存储到Session中
//        session.setAttribute("user",user);

        //3. 将登录成功的用户信息存储到Redis中
        String keySuffix = UUID.randomUUID().toString();
        String key = AirConstants.USER_REDIS_PREFIX + keySuffix;
        String value = JSONUtil.obj2JSON(user);
        stringRedisTemplate.opsForValue().set(key,value,AirConstants.USER_TIMEOUT, TimeUnit.SECONDS);
        // 写回Cookie
        Cookie cookie = new Cookie(AirConstants.USER_COOKIE,keySuffix);
        cookie.setMaxAge(999999999);
        cookie.setPath("/");
        resp.addCookie(cookie);

        //4. R.ok();
        return R.ok();
    }

}
